/****************************************Copyright (c)****************************************************
**                               China Mobile M2M Co., LTD
**
**                                 http://iot.10086.cn/
**
**--------------File Info---------------------------------------------------------------------------------
** File name:           api_socket.c
** Created by:          yangpengbo                  ID:03900265
** Created date:        20161118
** Version:             V1.00
** Descriptions:        creat file
**
**--------------------------------------------------------------------------------------------------------
** Modified by:         x
** Modified date:       x
** Version:             x
** Descriptions:        x
**
** Rechecked by:
*********************************************************************************************************/
#include "include.h"
/*********************************************************************************************************
**                                          MACRO DEF
*********************************************************************************************************/

/*********************************************************************************************************
**                                          ENUM&STRUCT
*********************************************************************************************************/

/*********************************************************************************************************
**                                          GLOBAL VAR
*********************************************************************************************************/
SocketInfoStruct    g_socketInfo = {0};
iot_S_SocketAddr    g_server_addr = {0};
/*********************************************************************************************************
**                                          LOCAL VAR
*********************************************************************************************************/
U8 *SOC_EVENT[]=
{
    "SOC_READ",
    "SOC_WRITE",
    "SOC_ACCEPT",
    "SOC_CONNECT",
    "SOC_CLOSE",
    "SOC_ACKED"
};

U8 *BEARER_STATE[]=
{
    "DEACTIVATED",
    "ACTIVATING",
    "ACTIVATED",
    "DEACTIVATING",
    "CSD_AUTO_DISC_TIMEOUT",
    "GPRS_AUTO_DISC_TIMEOUT",
    "NWK_NEG_QOS_MODIFY",
    "CBM_WIFI_STA_INFO_MODIF",
};
/*********************************************************************************************************
** Function name:       Socket_BearerNotify
** Descriptions:        Socket_BearerNotify
** input parameters:    state
**
** output parameters:   addr
** Returned value:      ret
*********************************************************************************************************/
void Socket_BearerNotify(S32 state, U8 *addr)
{
    U8 id = 0;

    if (state & IOT_BEARER_STATUS_DEACTIVATED) id = 0;
    else if (state & IOT_BEARER_STATUS_ACTIVATING) id = 1;
    else if (state & IOT_BEARER_STATUS_ACTIVATED) id = 2;
    else if (state & IOT_BEARER_STATUS_DEACTIVATING) id = 3;
    else if (state & IOT_BEARER_STATUS_CSD_AUTO_DISC_TIMEOUT) id = 4;
    else if (state & IOT_BEARER_STATUS_GPRS_AUTO_DISC_TIMEOUT) id = 5;
    else if (state & IOT_BEARER_STATUS_NWK_NEG_QOS_MODIFY) id = 6;
    else if (state & IOT_BEARER_STATUS_WIFI_STA_INFO_MODIFY) id = 7;

    iot_logDebug("%s,BEAR_NOTIFY:%s", __func__, BEARER_STATE[id]);

    if(id == 2)
        g_socketInfo.bearer_flag = TRUE;
    else
        g_socketInfo.bearer_flag = FALSE;
}
/*********************************************************************************************************
** Function name:       Server_GetHostByNameNotify
** Descriptions:        Server_GetHostByNameNotify
** input parameters:    none
** output parameters:   none
** Returned value:      return
*********************************************************************************************************/
void    Server_GetHostByNameNotify(BOOL result,U8 * addr,U8 addr_len)
{
    g_server_addr.port = device_getServerEndpoint();
    g_server_addr.addr[0] = addr[0];
    g_server_addr.addr[1] = addr[1];
    g_server_addr.addr[2] = addr[2];
    g_server_addr.addr[3] = addr[3];

    g_socketInfo.ip_flag = TRUE;

    iot_logInfo("server ip(%d.%d.%d.%d:%d)",
                 g_server_addr.addr[0], g_server_addr.addr[1], g_server_addr.addr[2], g_server_addr.addr[3],g_server_addr.port);
}
/*********************************************************************************************************
** Function name:       Socket_BearerOpen
** Descriptions:        Socket_BearerOpen
** input parameters:    none
** output parameters:   none
** Returned value:      ret
*********************************************************************************************************/
S8  Socket_BearerOpen(void)
{
    S8 ret;
    U8 ipaddr[4];
    U8 len;

    if(TRUE == gsm_specSimcardFlag())
        ret = iot_bearerOpen("CMMTM");
    else
        ret = iot_bearerOpen("CMNET");
	
    ret = iot_bearerHold();
	
    iot_logDebug("iot_gprsBearerHold return %d", ret);

    iot_setBearerStateNotifyFunc(Socket_BearerNotify);

	iot_logInfo("server url(%s)", device_getServerDomain());
    iot_socketGetHostByName(Server_GetHostByNameNotify, (void *)device_getServerDomain(), ipaddr, &len);

    return ret;
}
/*********************************************************************************************************
** Function name:       Socket_BearerClose
** Descriptions:        Socket_BearerClose
** input parameters:    none
** output parameters:   none
** Returned value:      ret
*********************************************************************************************************/
S8 Socket_BearerClose(void)
{
    S8 ret;
    ret = iot_bearerRelease();

    return ret;
}
/*********************************************************************************************************
** Function name:       Socket_GetBearerFlag
** Descriptions:        Socket_GetBearerFlag
** input parameters:    none
** output parameters:   none
** Returned value:      TRUE or FALSE
*********************************************************************************************************/
BOOL    Socket_BearerAndIpOk(void)
{
    if((TRUE == g_socketInfo.bearer_flag) &&(TRUE == g_socketInfo.ip_flag))
        return TRUE;
    else
        return FALSE;
}

/*********************************************************************************************************
** Function name:       Socket_CreatAndSetOpt
** Descriptions:        Socket_CreatAndSetOpt
** input parameters:    none
** output parameters:   none
** Returned value:      return
*********************************************************************************************************/
void    Server_SocketEventNotify(S8 soc_id,U8 event, BOOL result)
{
    S32 len = 0;
    U8  buff[512] = {0};

//    iot_logDebug("%s,event(%d), sid(%d),result(%d)", __func__, event,soc_id, result);

    if(event & IOT_SOC_READ)
    {
        while(1)
        {
            len = iot_socketRecv(soc_id, buff, sizeof(buff));

            if(len > 0)
            {
                g_socketInfo.recv_len = len;

                iot_memFree(g_socketInfo.recv_buff);
                g_socketInfo.recv_buff = iot_memAlloc((g_socketInfo.recv_len+1)*sizeof(U8));
                memset(g_socketInfo.recv_buff, 0, ((g_socketInfo.recv_len+1)*sizeof(U8)));
                memcpy(g_socketInfo.recv_buff, buff, g_socketInfo.recv_len);

                {
                    U8 *ptr;
                    U16 i;
                    memset(buff,0, sizeof(buff));
                    ptr = buff;
                    for(i=0; i<g_socketInfo.recv_len; i++, ptr +=2)
                        sprintf((void *)ptr, "%02X", g_socketInfo.recv_buff[i]);

                    iot_logInfo("Recv data=%s len=%d, sid=%d",buff, len, soc_id);
                }
                //send msg VDTP to handle
                iot_msgSend(iot_getActiveModId(),IOT_MOD_ID_TASK4,IOT_MSG_ID_SERVER_TCP_RECV,NULL,0);
            }
            else
                break;
        }
    }
    else if (event&IOT_SOC_CONNECT)
    {
        if(TRUE == result)
        {
            g_socketInfo.connect_flag = TRUE;
            g_socketInfo.sid = soc_id;
        }
        else
        {
            g_socketInfo.connect_flag = FALSE;
            g_socketInfo.sid = -1;
            iot_socketClose(soc_id);
            iot_logError("server connect fail");
        }
    }
    else if (event&IOT_SOC_CLOSE)
    {
        g_socketInfo.connect_flag = FALSE;
        iot_logDebug("----SOC_CLOSE---");
    }
}
/*********************************************************************************************************
** Function name:       Socket_CreatAndSetOpt
** Descriptions:        Socket_CreatAndSetOpt
** input parameters:    none
** output parameters:   none
** Returned value:      return
*********************************************************************************************************/
S8    Socket_ConnectServer(void)
{
    S8 sid;
    U8 val = 0;
    S8 ret = 0;

    sid = iot_socketCreate(IOT_SOC_SOCK_STREAM);
    iot_logDebug("iot_socketCreate return %d",sid);

    val = (IOT_SOC_READ | IOT_SOC_WRITE | IOT_SOC_CLOSE | IOT_SOC_CONNECT | IOT_SOC_ACCEPT);
    ret = iot_socketSetOpt(sid, IOT_SOC_ASYNC,&val,sizeof(val));

    if (ret != IOT_SOC_SUCCESS)
        iot_logDebug("iot_socketSetOpt 1 return error :%d",ret);

    val = TRUE;
    ret = iot_socketSetOpt(sid, IOT_SOC_NBIO, &val, sizeof(val));
    if (ret != IOT_SOC_SUCCESS)
        iot_logDebug("iot_socketSetOpt 2 return error :%d",ret);

    val = TRUE;
    ret = iot_socketSetOpt(sid, IOT_SOC_NODELAY, &val, sizeof(val));
    if (ret != IOT_SOC_SUCCESS)
        iot_logDebug("iot_socketSetOpt 3 return error :%d",ret);

    iot_setSocketEventCallBackFunc(sid, Server_SocketEventNotify);

    ret = iot_socketConnect(sid,&g_server_addr);

    if(ret >= 0)
    {
        iot_logDebug("NEW Connection ID is :%d",ret);
    }
    else if (ret == IOT_SOC_WOULDBLOCK)
    {
        iot_logDebug("Connection is in progressing");
    }
    else
    {
        iot_logDebug("Connect return error:%d",ret);
    }

    return sid;
}

BOOL    Socket_GetServerConnectFlag(void)
{
    return g_socketInfo.connect_flag;
}
void    Socket_SetServerConnectFlag(BOOL flag)
{
    g_socketInfo.connect_flag = flag;
}

/*********************************************************************************************************
End Of File
*********************************************************************************************************/

